package com.tao.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tao.media.domain.pojo.MediaFiles;
import com.tao.media.domain.pojo.MediaProcess;
import com.tao.media.domain.pojo.MediaProcessHistory;
import com.tao.media.mapper.MediaFilesMapper;
import com.tao.media.mapper.MediaProcessHistoryMapper;
import com.tao.media.mapper.MediaProcessMapper;
import com.tao.media.service.IMediaProcessService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author taohongrun
 * @since 2024-11-05
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MediaProcessServiceImpl extends ServiceImpl<MediaProcessMapper, MediaProcess> implements IMediaProcessService {

    final MediaProcessMapper mediaProcessMapper;
    final MediaFilesMapper mediaFilesMapper;
    final MediaProcessHistoryMapper mediaProcessHistoryMapper;
    @Override
    public List<MediaProcess> getProcess(Integer shardTotal, Integer shardIndex, Integer count) {
        return mediaProcessMapper.selectProcess(shardTotal,shardIndex,count);
    }

    @Override
    public boolean startProcess(Long id) {
        //下边使用乐观锁的方式实现更新操作：
        //update media_process m set m.status='4' where (m.status='1' or m.status='3') and m.fail_count<3 and m.id=?
        boolean update = lambdaUpdate().set(MediaProcess::getStatus, "4")
                .lt(MediaProcess::getFailCount, 3)
                .eq(MediaProcess::getId, id)
                .and(i -> i
                        .eq(MediaProcess::getStatus, "1")
                        .or()
                        .eq(MediaProcess::getStatus, "3"))
                .update();
        return update;
    }

    @Override
    public void saveProcessFinishStatus(Long id,String status,String fileId,String url,String errorMessage) {
        MediaProcess mediaProcess = mediaProcessMapper.selectById(id);
        if(mediaProcess == null){
            return ;
        }
        //处理失败，更新任务处理结果
        LambdaQueryWrapper<MediaProcess> queryWrapperById = new LambdaQueryWrapper<MediaProcess>().eq(MediaProcess::getId, id);
        //处理失败
        if(status.equals("3")){
            MediaProcess mediaProcess_u = new MediaProcess();
            mediaProcess_u.setStatus("3");
            mediaProcess_u.setErrormsg(errorMessage);
            mediaProcess_u.setFailCount(mediaProcess.getFailCount()+1);
            mediaProcessMapper.update(mediaProcess_u,queryWrapperById);
            log.debug("更新任务处理状态为失败，任务信息:{}",mediaProcess_u);
            return ;
        }
        //任务处理成功
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileId);
        if(mediaFiles!=null){
            //更新媒资文件中的访问url
            mediaFiles.setUrl(url);
            mediaFilesMapper.updateById(mediaFiles);
        }
        //处理成功，更新url和状态
        mediaProcess.setUrl(url);
        mediaProcess.setStatus("2");
        mediaProcess.setFinishDate(LocalDateTime.now());
        mediaProcessMapper.updateById(mediaProcess);

        //添加到历史记录
        MediaProcessHistory mediaProcessHistory = new MediaProcessHistory();
        BeanUtils.copyProperties(mediaProcess, mediaProcessHistory);
        mediaProcessHistory.setId(null);
        mediaProcessHistoryMapper.insert(mediaProcessHistory);
        //删除mediaProcess
        mediaProcessMapper.deleteById(mediaProcess.getId());

    }
}
